const bcryptjs = require("bcryptjs") // 加密
const hash = bcryptjs.genSaltSync(10) // 生成加密hash
const { decrypt } = require("../auth/jsencrypt.js") // 解密方法，和bcryptjs不是同一个插件
const JWT = require("jsonwebtoken") // 生成token
const routers = require("../mock/router") // 路由
const { secretKey, tokenTime } = require("../auth/global.js")
const query = require("../sql/db")

const methods = {
  // 登录
  login: (req, res) => {
    const { username, password } = req.body
    const jwt_token = JWT.sign({ username }, secretKey, {
      expiresIn: tokenTime,
    })
    if (username === "admin") {
      res.success({
        token: jwt_token,
      })
      return
    }
    const validSql = `select password from t_user where user_name = '${username}'`
    query(validSql, (vErr, vResult) => {
      if (vResult.length) {
        const userPassword = vResult[0].password // 获取数据库中用户密码
        const password_web = decrypt(password) // 对客户端密码进行解密
        const validable = bcryptjs.compareSync(password_web, userPassword)
        if (!validable) {
          res.fail("用户名密码错误")
        } else {
          res.success({
            token: jwt_token,
          })
        }
      } else {
        res.fail("用户名不存在")
      }
    })
  },
  // 注册
  register: (req, res) => {
    const { username, password, userId } = req.body

    const validSql = `select * from t_user where user_name = '${username}'`
    query(validSql, (vErr, vResult) => {
      if (vResult.length) {
        res.fali("用户名已存在")
      } else {
        const password_web = decrypt(password) // 对客户端密码进行解密
        const password_en = bcryptjs.hashSync(password_web, hash) // 对原密码进行加密
        const sql = `insert into t_user (user_name, password, createBy, create_time) values ('${username}', '${password_en}', ${
          userId || null
        }, now())`
        query(sql, (err, result) => {
          if (err) {
            res.fail("新增失败", { data: err })
          } else {
            res.success()
          }
        })
      }
    })
  },
  // 登出
  logout: (req, res) => {
    res.success()
  },
  // 获取用户信息
  getInfo: (req, res) => {
    res.send({
      msg: "操作成功",
      code: 200,
      permissions: ["*:*:*"],
      roles: ["admin"],
      user: {
        createBy: "admin",
        createTime: "2023-04-23 16:11:38",
        updateBy: null,
        updateTime: null,
        remark: "管理员",
        userId: 1,
        deptId: 103,
        userName: "admin",
        nickName: "若依",
        email: "ry@163.com",
        phonenumber: "15888888888",
        sex: "1",
        avatar: "",
        password:
          "$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2",
        status: "0",
        delFlag: "0",
        loginIp: "124.89.238.230",
        loginDate: "2023-12-06T15:53:08.000+08:00",
        dept: {
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null,
          deptId: 103,
          parentId: 101,
          ancestors: "0,100,101",
          deptName: "研发部门",
          orderNum: 1,
          leader: "若依",
          phone: null,
          email: null,
          status: "0",
          delFlag: null,
          parentName: null,
          children: [],
        },
        roles: [
          {
            createBy: null,
            createTime: null,
            updateBy: null,
            updateTime: null,
            remark: null,
            roleId: 1,
            roleName: "超级管理员",
            roleKey: "admin",
            roleSort: 1,
            dataScope: "1",
            menuCheckStrictly: false,
            deptCheckStrictly: false,
            status: "0",
            delFlag: null,
            flag: false,
            menuIds: null,
            deptIds: null,
            permissions: null,
            admin: true,
          },
        ],
        roleIds: null,
        postIds: null,
        roleId: null,
        admin: true,
      },
    })
  },
  // 获取用户权限
  getRouters: (req, res) => {
    res.success({
      data: routers,
    })
  },
}

module.exports = methods
